<script setup lang="ts">
import { onMounted, reactive, h, ref } from 'vue';
import { useMessage, NCard, NDataTable, NButton, NSpace, NModal } from 'naive-ui';
import CreateStore from './CreateStore.vue';
import statusCode from '../api/statusCode';
import { getToken } from '../util/token';
import { handleNoToken } from '../util/handler';
import { findAllStore, StoreInfo } from '../api/store';
import router from '../router';
import { defer } from '../util/decorator';

const message = useMessage();

const storeInfos = reactive<StoreInfo[]>([]);

const queryAllStore = async () => {
  const token = getToken();
  if (!token) {
    handleNoToken(message);
    return [];
  }

  try {
    const resp = await findAllStore(token);

    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else if (resp.status === statusCode.QUERY_ALL_STORES_FAILED) {
      // user has no store.
      return [];
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
    return [];
  }
};

const createColumns = ({ handleRowData }: { handleRowData: (rowData: StoreInfo) => void }) => {
  return [
    {
      title: '店铺编号',
      key: 'storeId'
    },
    {
      title: '店铺名称',
      key: 'storeName'
    },
    {
      key: 'actions',
      render(row: StoreInfo) {
        return h(
          NButton,
          {
            size: 'small',
            onClick: () => handleRowData(row)
          },
          { default: () => '管理' }
        )
      }
    }
  ]
};

const columns = createColumns({
  handleRowData: (row) => router.push({ name: 'userStore', params: { storeId: row.storeId } })
});

const tableLoading = ref(true);

const createStoreTable = async () => {
  tableLoading.value = true;

  try {
    const stores = await queryAllStore();
    storeInfos.length = 0;
    storeInfos.push(...stores);
  } catch (error) {
    message.error('' + error);
  } finally {
    tableLoading.value = false;
  }
};

const handleCreateProduct = () => (showNewStore.value = true);

const refreshList = createStoreTable;

const deferedCreateProductTable = defer(refreshList);

onMounted(createStoreTable);

const showNewStore = ref(false);
</script>

<template>
  <n-card title="店铺列表">
    <n-space
      vertical
      size="large"
    >
      <n-space size="medium">
        <n-button
          type="primary"
          @click="handleCreateProduct"
        >
          新建店铺
        </n-button>
        <n-button
          type="default"
          @click="deferedCreateProductTable"
        >
          刷新
        </n-button>
      </n-space>
      <n-data-table
        :loading="tableLoading"
        :columns="columns"
        :data="storeInfos"
        :pagination="{ pageSize: 10 }"
      />
    </n-space>
  </n-card>

  <n-modal
    v-model:show="showNewStore"
    :mask-closable="false"
    class="modal"
  >
    <create-store
      @close-store="showNewStore = false"
      @refresh-list="refreshList"
    />
  </n-modal>
</template>

<style scoped>
</style>
